package com.mycompany.view.web.pages.welcome;

import java.util.ArrayList;
import java.util.Collection;
import java.util.EnumSet;
import java.util.List;

import org.apache.wicket.behavior.SimpleAttributeModifier;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.image.Image;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.StringResourceModel;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import com.facebook.api.FacebookException;
import com.facebook.api.FacebookRestClient;
import com.facebook.api.ProfileField;
import com.mycompany.view.web.facebookIntegration.FacebookSession;


@SuppressWarnings("serial")
public class LoginPage extends WebPage {

	public LoginPage(){
		try{
			FacebookRestClient client = ((FacebookSession)getSession()).getClient();
			if(client== null){
				WebMarkupContainer friends = new WebMarkupContainer("friends");
				friends.add(new Label("friend", "missing friends"));
				add(friends);
			}
			else{
				// Logged in user
				long myId = client.users_getLoggedInUser();
				EnumSet<ProfileField> fields = EnumSet.of(
						com.facebook.api.ProfileField.NAME,
						com.facebook.api.ProfileField.PIC
				);
				
				Collection<Long> userIds = new ArrayList<Long>();
				userIds.add(myId);
				Document doc =  client.users_getInfo(userIds, fields);
				String name = doc.getElementsByTagName("name").item(0).getTextContent();

				add(new Label("welcomeMsg", getMessage(this, "welcome.message", new Object[]{name})));

				add( new ListView("photos", getPicturesUrl(doc.getElementsByTagName("pic"))){
					@Override
					protected void populateItem(ListItem item) {
						Image image = new Image("image");
						image.add(new SimpleAttributeModifier("src", item.getModelObjectAsString()));
						item.add(image);
					}
				});
			}
		}
		catch(FacebookException fbe){
			throw new RuntimeException(fbe);
		}
		
		catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	
	private List<String> getPicturesUrl(NodeList nodes){
		List<String> res = new ArrayList<String>();
		for(int i=0; i< nodes.getLength(); i++){
			res.add(nodes.item(i).getTextContent());
		}
		return res;
	}
	
	protected String getMessage(WebPage page, String key, Object[] args){
		return (new StringResourceModel(key, page, new Model(), args )).getString();
	}
}
